<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Route;
use Log;

/**
 * 后台权限检查中间件
 * @package App\Http\Middleware
 */
class AdminCheckPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $curRoute = $request->route();
        $curRouteName = $curRoute[1]['as'] ?? '';
        //登录不做权限校验
        if ($curRouteName == 'admin.login.account'){
            return $next($request);
        }
        if (empty($request->user())){
            throw new \Exception('用户登录已过期，请重新登录', 401);
        }
        if (Gate::denies('rbac', $curRouteName)) {
            return response()->json([
                'code'=>403,
                'message'=>'您未被授权访问',
                'data'=>[]
            ], 403);
        }
        return $next($request);
    }
}
